<template>
  <div>
    <el-form ref="from" :model="form" label-width="120px" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option v-for="item in List" :key="item.id" :label="item.username" :value="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="add">确定</el-button>
        <el-button size="small" @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { addDepartment, getUser, setMout, getIdUser } from '@/api/departments'

export default {

  props: {
    // 接口需要的id
    parentid: {
      type: [Number, String],
      required: true
    },
    isedit: { // 用来判断时删除状态还是修改状态
      type: [Boolean],
      required: true
    },
    alllist: {
      type: Array,
      required: true
    },
    // 处理后的数组 接收
    newList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 自定义表单验证
    const validcode = (rule, value, callback) => {
      // 如果处于添加状态
      // 拿到code 放入数组 判断
      let codeList = this.newList.map(item => item.code)

      // 处于修改状态
      // 把自己的code 重数组中 去掉（筛选出去） 然后生产新的code数组 在其中判断
      if (this.isedit) {
        codeList = this.newList.filter(item => item.id !== this.parentid).map(item => item.name)
      }
      codeList.includes(value) ? callback(new Error(`已有重复的${value}`)) : callback()
    }
    // 自定义表单验证2
    // 下属的pid 等于 上司的 id
    const validname = (rule, value, callback) => {
      let nameList = this.newList.filter(item => item.pid === this.parentid).map(item => item.name)
      // 编辑状态
      if (this.isedit) {
        // 拿到点击的id（点击那一项）
        const obj = this.newList.filter(item => item.id === this.parentid)
        // 通过点击的那一项 获得所有pid相同的（所有的子集）然后通过id 去掉在数组中（验证数组nameList）自己（防止编辑状态下 数据回显默认报重复）
        nameList = this.newList.filter(item => item.pid === obj.pid && item.id !== obj.id)
      }
      nameList.includes(value) ? callback(new Error(`已有重复的${value}`)) : callback()
    }
    return {
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      List: [], // 负责人列表
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validname, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: validcode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  async created() {
    // 获取负责人列表
    const res = await getUser()
    this.List = res.data
    console.log(res)
    // 回显 只在编辑状态下执行
    this.getIdUser()
    // console.log(this.alllist)
    console.log(this.newList)
  },
  methods: {

    add() {
      // 兜底验证
      this.$refs.from.validate(valid => {
        if (valid) {
          // 点击确定 新增部门或者修改部门
          if (this.isedit) {
            this.setMout()
          } else {
            this.addMoit()
          }
        }
      })
    },
    cancel() {
      // 点击取消
      this.$emit('closepopUp', false)
      this.$message.info('已取消')
    },
    // 修改部门的函数
    async setMout() {
      const res = await setMout({ ...this.form }, this.parentid)
      console.log(res)
      this.$emit('closepopUp', false)
      this.$message.success(res.message)
    },
    // 增加部门的函数
    async addMoit() {
      const res = await addDepartment({ ...this.form, pid: this.parentid })
      console.log(res)
      this.$emit('closepopUp', false)
      this.$message.success(res.message)
    },
    // 数据回显
    async  getIdUser() {
      // 修改的状态才会回显
      if (this.isedit) {
        const res2 = await getIdUser(this.parentid)
        this.form = res2.data
      }
    }

  }
}
</script>

<style>

</style>
